package com.wly.packet;

import java.lang.reflect.Method;

import org.apache.mina.core.buffer.IoBuffer;

import com.google.protobuf.Message;

public abstract class Packet
{
	public Message content;
	static private final String PARSE_METHOD_NAME = "parseFrom";
	
	@SuppressWarnings("unchecked")
	public Boolean unSerialization(byte[] byteArr) throws Exception
	{
		if(getGPBClassName() == null)
		{
			return false;
		}
		
		Class cls = Class.forName(getGPBClassName());
		Method parseMethod = cls.getMethod(PARSE_METHOD_NAME, byte[].class);
		content = (Message)parseMethod.invoke(null, byteArr);
		return true;
	}
	
	public IoBuffer serialization()
	{
		IoBuffer buff = IoBuffer.allocate(2048).setAutoExpand(true);
		if(content != null)
		{
			buff.putShort((short)content.getSerializedSize());
			buff.putShort((short)getPacketID());
			buff.put(content.toByteArray());
			buff.flip();
		}
		return buff;
	}
	
	public abstract int getPacketID();
	protected abstract String getGPBClassName();
}
